import constant from '../../constant';
import storage from '../../utils/storage'
import defaultDepts from '../data/depts.json'
import { getTree, childs } from '../../utils/tree'

let dataName = 'departments'
let data = storage.getOrDefault(dataName, defaultDepts)

export default [
    {
        url: constant.API.SYSTEM.DEPT.LIST,
        type: 'post',
        response: (config) => {
            return {"code":1000,"message":"success","data": storage.getOrDefault(dataName, data)}
        }
    },
    {
        url: constant.API.SYSTEM.DEPT.ADD,
        type: 'post',
        response: (config) => {
            let dept = config.body
            if (dept) {
                dept.id = new Date().getTime() + ""
                dept.createTime = new Date().format("yyyy-MM-dd HH:mm:ss")
                dept.updateTime = new Date().format("yyyy-MM-dd HH:mm:ss")
                data.push(dept)
                storage.set(dataName, data)
            }
            return {
                "code": 1000,
                "message": "success"
            }
        }
    },
    {
        url: constant.API.SYSTEM.DEPT.UPDATE,
        type: 'post',
        response: (config) => {
            let dept = config.body
            if (dept) {
                let ds = data.filter(d=>d.id===dept.id)
                let target = ds.length > 0 ? ds[0] : null
                if (target) {
                    target.name = dept.name
                    target.orderNum = dept.orderNum
                    target.parentId = dept.parentId
                    target.parentName = dept.parentName
                    storage.set(dataName, data)
                }
            }
            return {
                "code": 1000,
                "message": "success"
            }
        }
    },
    {
        url: constant.API.SYSTEM.DEPT.DELETE,
        type: 'post',
        response: (config) => {
            let dept = config.body
            if (dept) {
                let allDeleteIds = childs(data, dept.ids).map(e=>e.id)
                data = data.filter(e => !allDeleteIds.includes(e.id))
                storage.set(dataName, data)
            }
            return {
                "code": 1000,
                "message": "success"
            }
        }
    },
    {
        url: constant.API.SYSTEM.DEPT.ORDER,
        type: 'post',
        response: (config) => {
            let deptList = config.body
            if (deptList) {
                let deptMap = {}
                deptList.map((e) => {
                    deptMap[e.id] = e
                })
                data.forEach((d) => {
                    if (deptMap[d.id]) {
                        d.parentId = deptMap[d.id].parentId
                        d.orderNum = deptMap[d.id].orderNum
                    }
                })
                storage.set(dataName, data)
            }
            return {
                "code": 1000,
                "message": "success"
            }
        }
    }
]
